/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2012/07/26
* File: OGLDepthStencilRenderTarget.cpp
* Blog: http://www.cnblogs.com/zengqh/
**/

#include "OGLFrameBuffer.h"
#include "OGLDepthStencilRenderTarget.h"

OGLDepthStencilRenderTarget::OGLDepthStencilRenderTarget(const Dimension2Di& size)
: DepthStencilRenderTarget(size)
, _rbo(0)
{
	setup();
}

OGLDepthStencilRenderTarget::~OGLDepthStencilRenderTarget()
{
	if (_rbo != 0)
	{
		glDeleteRenderbuffers(1, &_rbo);
	}
}


void OGLDepthStencilRenderTarget::onAttached(FrameBuffer* fb, u32 att)
{
	OGLFrameBuffer* ogl_fb = static_cast<OGLFrameBuffer*>(fb);

	glBindFramebuffer(GL_FRAMEBUFFER, ogl_fb->getFBO());

	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _rbo);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void OGLDepthStencilRenderTarget::onDetached(FrameBuffer* fb, u32 att)
{
	OGLFrameBuffer* ogl_fb = static_cast<OGLFrameBuffer*>(fb);

	glBindFramebuffer(GL_FRAMEBUFFER, ogl_fb->getFBO());

	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

GLuint OGLDepthStencilRenderTarget::getRBO() const
{
	return _rbo;
}

void OGLDepthStencilRenderTarget::setup()
{
	glGenRenderbuffers(1, &_rbo);

	glBindRenderbuffer(GL_RENDERBUFFER, _rbo);

	glRenderbufferStorage(GL_RENDERBUFFER,
		GL_DEPTH_COMPONENT, _width, _height);

	glBindRenderbuffer(GL_RENDERBUFFER, 0);
}